﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Psl.Applications;
using Psl.Chat;
using System.Threading;

namespace Stl.Chat.Services.Plugin
{
    public partial class ChatMsgGenerator : UserControl
    {
        // Les deux mode de générateurs
        public enum GeneratorType
        {
            Timer,
            Thread
        };

        /************************************************************
         *                          Champs                          *
         ************************************************************/
        protected IChat model;

        protected string generatorName = "generator";

        protected string generatedMsg = GeneratorConfigDialog.DefaultMessage;

        protected int count = 1;

        private int interval = GeneratorConfigDialog.DefaultInterval;
        private BackgroundWorker worker = new BackgroundWorker();

        // Le mode programmé dans la configuration
        private GeneratorType configMode = GeneratorConfigDialog.DefaultMode;
        // Le mode current, il est utile dans le cas où on modifie le mode après avoir lancé le générateur
        private GeneratorType curMode = GeneratorConfigDialog.DefaultMode;


        /************************************************************
         *                        Constructeur                      *
         ************************************************************/
        public ChatMsgGenerator()
        {
            InitializeComponent();
            
            Registry.MergeInMainMenu(menuStrip);
            Registry.MergeInMainTools(toolStrip);
            startAction.Enabled = false;
            stopAction.Enabled = false;

            // set interval du timer
            timer.Interval = interval;

            // worker
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += WorkerWork;
        }


        /************************************************************
         *                         Evenements                       *
         ************************************************************/
        private void showToolsAction_Execute(object sender, EventArgs e)
        {
            showToolsAction.Checked = !showToolsAction.Checked;
            toolStrip.Visible = showToolsAction.Checked;
        }

        private void startAction_Execute(object sender, EventArgs e)
        {
            startAction.Enabled = false;
            stopAction.Enabled = true;
            Start();
        }

        private void stopAction_Execute(object sender, EventArgs e)
        {
            stopAction.Enabled = false;
            startAction.Enabled = true;
            Stop();
        }

        private void setIntervalAction_Execute(object sender, EventArgs e)
        {
            using (GeneratorConfigDialog dialog = new GeneratorConfigDialog(interval, generatedMsg, configMode))
            {
                DialogResult res = dialog.ShowDialog();
                if (res == DialogResult.OK)
                {
                    interval = dialog.Interval;
                    timer.Interval = interval;
                    generatedMsg = dialog.Message;
                    configMode = dialog.Mode;
                    MessageBox.Show("Succes : Configurations de générateur de messages enregistrées.");
                }
            }
        }
        

        private void chatEvents_ChatOpened(object sender, EventArgs e)
        {
            model = ChatRegistry.ChatState.ModelInternal;
            startAction.Enabled = true;
            stopAction.Enabled = false;
        }

        private void chatEvents_ChatClosing(object sender, EventArgs e)
        {
            Stop();
            startAction.Enabled = false;
            stopAction.Enabled = false;
        }

        private void chatEvents_ChatClosed(object sender, EventArgs e)
        {

        }


        private void timer_Tick(object sender, EventArgs e)
        {
            GenerateMessage();
        }

        private void applicationEvents_Archive(IArchiver sender)
        {
            sender.PushSection("Stl.Chat.Services.Plugin.ChatMsgGenerator");
            try
            {
                sender.ArchiveProperty("Checked", showToolsAction, false);
            }
            finally { sender.PopSection(); }

            if (sender.IsReading)
                toolStrip.Visible = showToolsAction.Checked;      // a revoir
        }


        /************************************************************
         *                          Méthodes                        *
         ************************************************************/
        private void GenerateMessage()
        {
            if (model != null)
                model.Add(generatorName, generatedMsg + " " + (count++));
        }

        // BackgroundWorker
        protected void WorkerWork(object sender, EventArgs e)
        {
            while (!(sender as BackgroundWorker).CancellationPending)
            {
                GenerateMessage();
                Thread.Sleep(interval);
            }
        }

        public void Start()
        {
            count = 0;
            curMode = configMode;
            if (configMode == GeneratorType.Thread)
            {
                worker.RunWorkerAsync();
            }
            else    // GeneratorType.Timer
            {
                timer.Start();
            }
        }

        public void Stop()
        {
            if (curMode == GeneratorType.Thread)
            {
                worker.CancelAsync();
            }
            else    // GeneratorType.Timer
            {
                timer.Stop();
            }

        }

        private void aboutgenerator_Execute(object sender, EventArgs e)
        {
            (new Psl.Applications.StandardAboutForm("Plugin permetant de générer des messages.", "Bo CAI, Fabrice Reynaud", null)).ShowDialog();
        }

    }
}
